﻿using System.Security.Cryptography;
using System.Text;

namespace MultiAgentsServer.Scripts.Services;

public class EncryptService
{
    public static string GenerateSalt(int length)
    {
        const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new();
        char[] salt = new char[length];

        for (int i = 0; i < length; i++)
        {
            salt[i] = validChars[random.Next(validChars.Length)];
        }

        return new string(salt);
    }

    public static string AddSaltToPassword(string password, string salt)
    {
        string saltedPassword = password + salt;
        return saltedPassword;
    }

    public static string HashPassword(string password, Func<byte[], byte[]> hashFunction)
    {
        byte[] bytes = hashFunction(Encoding.UTF8.GetBytes(password));

        StringBuilder builder = new();
        for (int i = 0; i < bytes.Length; i++)
        {
            builder.Append(bytes[i].ToString("x2"));
        }
        return builder.ToString();
    }

    public static byte[] MD5HashFunction(byte[] data)
    {
        return MD5.HashData(data);
    }

    public static byte[] SHA256HashFunction(byte[] data)
    {
        return SHA256.HashData(data);
    }

    public static byte[] SHA512HashFunction(byte[] data)
    {
        return SHA512.HashData(data);
    }

    public static string EncryptPassword(string password, string salt, Func<byte[], byte[]> hashFunction)
    {
        string saltedPassword = AddSaltToPassword(password, salt);

        return HashPassword(saltedPassword, hashFunction);
    }

    public static string EncryptString(string str, Func<byte[], byte[]> hashFunction)
    {
        return HashPassword(str, hashFunction);
    }
}